import _ from 'lodash';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';

import * as api from '@/services/ContractPlanMgr';

dayjs.extend(utc);

const initData = {
  // years months
  initYear: new Date().getUTCFullYear(),
  year: null,
  month: new Date().getMonth() + 1,
  signDates: [],
  products: [],
  projectProducts: [],
  affiliationMonth: '',
  supplyPlanItems: [],
  contractPlanItems: [],
  signPlanVersionId: '',
  canSignRoomCount: null,
  canSignPrice: null,
  isParking: 0,
  supplySize: 0,
  supplyPlanSize: 0,
  supplyActualSize: 0,
  signDetailProductDto: {
    businessType: '',
    businessTypeName: '',
    freeType: '',
    freeTypeName: '',
    groupId: '',
    groupName: '',
    proType: '',
    proTypeName: '',
    productCode: '',
    productName: '',
    versionId: '',
  },
};

// 根据签约计划生成签约年月
const recalculateSignDates = list => {
  const signDates = [];
  let years = [];
  // const month = new Date().getMonth() + 1;
  // 生成年份数组
  const firstPlan = list[0];
  list.forEach(element => {
    if (element.signPlanTime) {
      const year = new Date(element.signPlanTime).getFullYear();
      years = _.union(years, [year]);
    }
  });
  let minYear = new Date().getFullYear();
  if (years.length > 0) {
    minYear = years[0];
  }
  const maxYear = new Date().getFullYear();
  for (let i = minYear; i <= maxYear; i += 1) {
    years = _.union(years, [i]);
  }
  // 生成月份数组
  years.forEach(year => {
    const signDateItem = {
      key: year,
      removable: false,
      months: [],
    };
    for (let i = 1; i < 13; i += 1) {
      // 本月开始有供货计划就可以点
      let clickable = true;
      if (dayjs(new Date(year, i - 1, 1)) < dayjs(firstPlan.signPlanTime)) {
        clickable = false;
      }
      let editable = true;
      if (new Date(year, i - 1, 1) < new Date(new Date().getFullYear(), new Date().getMonth(), 1)) {
        editable = false;
      }
      signDateItem.months.push({
        key: i,
        clickable,
        editable,
      });
    }
    signDates.push(signDateItem);
  });
  return signDates;
};
const addSignDate = list => {
  let year = _.last(list);
  if (year && year.key >= new Date().getFullYear()) {
    year = year.key + 1;
  } else {
    year = new Date().getFullYear();
  }
  const signDates = _.cloneDeep(list);
  const signDateItem = {
    key: year,
    removable: year > new Date().getFullYear(),
    months: [],
  };
  for (let i = 1; i < 13; i += 1) {
    signDateItem.months.push({
      key: i,
      clickable: true,
      editable: true,
    });
  }
  signDates.push(signDateItem);
  return signDates;
};
const formatBaseAttr = itemx => {
  const item = itemx;
  item.isParking = _.toNumber(item.isParking);
  item.earlyAvgPrice = _.toNumber(item.earlyAvgPrice);
  item.earlyAvgRoomArea = _.toNumber(item.earlyAvgRoomArea);
  item.earlyCanSignRoomCount = _.toNumber(item.earlyCanSignRoomCount);
  item.earlyRoomArea = _.toNumber(item.earlyRoomArea);
  item.earlyRoomCount = _.toNumber(item.earlyRoomCount);
  item.earlySignAvgPrice = _.toNumber(item.earlySignAvgPrice);
  item.earlySignRoomArea = _.toNumber(item.earlySignRoomArea);
  item.earlySignRoomCount = _.toNumber(item.earlySignRoomCount);
  item.earlySignSumPrice = _.toNumber(item.earlySignSumPrice);
  item.earlySumPrice = _.toNumber(item.earlySumPrice);
  item.statisticsAvgPrice = _.toNumber(item.statisticsAvgPrice);
  item.statisticsAvgRoomArea = _.toNumber(item.statisticsAvgRoomArea);
  item.statisticsCanSignRoomCount = _.toNumber(item.statisticsCanSignRoomCount);
  item.statisticsRoomArea = _.toNumber(item.statisticsRoomArea);
  item.statisticsRoomCount = _.toNumber(item.statisticsRoomCount);
  item.statisticsSignAvgPrice = _.toNumber(item.statisticsSignAvgPrice);
  item.statisticsSignRoomArea = _.toNumber(item.statisticsSignRoomArea);
  item.statisticsSignRoomCount = _.toNumber(item.statisticsSignRoomCount);
  item.statisticsSignSumPrice = _.toNumber(item.statisticsSignSumPrice);
  item.statisticsSumPrice = _.toNumber(item.statisticsSumPrice);
  item.supplyAvgPrice = _.toNumber(item.supplyAvgPrice);
  item.supplyAvgRoomArea = _.toNumber(item.supplyAvgRoomArea);
  item.supplyCanSignRoomCount = _.toNumber(item.supplyCanSignRoomCount);
  item.supplyRoomArea = _.toNumber(item.supplyRoomArea);
  item.supplyRoomCount = _.toNumber(item.supplyRoomCount);
  item.supplySignAvgPrice = _.toNumber(item.supplySignAvgPrice);
  item.supplySignRoomArea = _.toNumber(item.supplySignRoomArea);
  item.supplySignRoomCount = _.toNumber(item.supplySignRoomCount);
  item.supplySignSumPrice = _.toNumber(item.supplySignSumPrice);
  item.supplySumPrice = _.toNumber(item.supplySumPrice);
  item.signPlanTime = dayjs(item.signPlanTime);
  return item;
};

const recalculatePlans = (signDates, list, affiliationMonth) => {
  const { isParking } = _.first(list);
  const plans = [];
  signDates.forEach(elementYear => {
    if (elementYear.months && elementYear.months.length > -1) {
      elementYear.months.forEach(elementMonth => {
        const foundItems = _.filter(list, item => {
          const year = dayjs(item.signPlanTime).year();
          const month = dayjs(item.signPlanTime).month() + 1;
          if (elementYear.key === year && elementMonth.key === month) {
            return true;
          }
          return false;
        });

        const preItemDate = dayjs(new Date(elementYear.key, elementMonth.key - 1, 1)).add(
          -1,
          'month',
        );
        let preItems = _.filter(plans, item => {
          if (
            dayjs(preItemDate).month() === dayjs(item.signPlanTime).month() &&
            dayjs(preItemDate).year() === dayjs(item.signPlanTime).year()
          ) {
            return true;
          }
          return false;
        });

        let preItem = null;
        if (preItems && preItems.length > 0) {
          preItem = preItems[0];
          preItem = formatBaseAttr(preItem);
        } else {
          preItems = _.filter(list, item => {
            if (
              dayjs(preItemDate).month() === dayjs(item.signPlanTime).month() &&
              dayjs(preItemDate).year() === dayjs(item.signPlanTime).year()
            ) {
              return true;
            }
            return false;
          });
          if (preItems && preItems.length > 0) {
            preItem = preItems[0];
            preItem = formatBaseAttr(preItem);
          }
        }

        let item = {
          editable: true,
          year: elementYear.key,
          month: elementMonth.key,
          signPlanTime: dayjs(new Date(elementYear.key, elementMonth.key - 1, 1)),
          earlyAvgPrice: 0,
          earlyAvgRoomArea: 0,
          earlyCanSignRoomCount: 0,
          earlyRoomArea: 0,
          earlyRoomCount: 0,
          earlySignAvgPrice: 0,
          earlySignRoomArea: 0,
          earlySignRoomCount: 0,
          earlySignSumPrice: 0,
          earlySumPrice: 0,
          statisticsAvgPrice: 0,
          statisticsAvgRoomArea: 0,
          statisticsCanSignRoomCount: 0,
          statisticsRoomArea: 0,
          statisticsRoomCount: 0,
          statisticsSignAvgPrice: 0,
          statisticsSignRoomArea: 0,
          statisticsSignRoomCount: 0,
          statisticsSignSumPrice: 0,
          statisticsSumPrice: 0,
          errorEarlySignSumPrice: false,
          errorSupplySignSumPrice: false,
          supplyAvgPrice: 0,
          supplyAvgRoomArea: 0,
          supplyCanSignRoomCount: 0,
          supplyRoomArea: 0,
          supplyRoomCount: 0,
          supplySignAvgPrice: 0,
          supplySignRoomArea: 0,
          supplySignRoomCount: 0,
          supplySignSumPrice: 0,
          supplySumPrice: 0,
          isParking,
        };
        if (foundItems && foundItems.length > 0) {
          item = {
            ...item,
            ...foundItems[0],
          };
        }
        item.editable = (item.isLock ? item.isLock * 1 === 0 : true) && elementMonth.editable;
        item = formatBaseAttr(item);
        // 取计划值  earlyAvgRoomArea
        if (dayjs(item.signPlanTime) >= dayjs(affiliationMonth)) {
          // 套数 = (月初存货-剩余可签套数) + (本月新供-剩余可签套数)
          item.earlyRoomCount = _.round(
            preItem
              ? _.toNumber(preItem.earlyCanSignRoomCount) +
                  _.toNumber(preItem.supplyCanSignRoomCount)
              : _.toNumber(item.earlyRoomCount),
            5,
          );
          if (isParking * 1 === 1) {
            item.earlyRoomArea = null; // 面积
            item.earlyAvgRoomArea = null; // 套均面积
          } else {
            item.earlyRoomArea = _.round(
              preItem
                ? _.toNumber(preItem.statisticsRoomArea) -
                    _.toNumber(preItem.statisticsSignRoomArea)
                : _.toNumber(item.earlyRoomArea),
              4,
            );
            item.earlyAvgRoomArea = _.round(
              item.earlyRoomCount
                ? _.toNumber(item.earlyRoomArea) / _.toNumber(item.earlyRoomCount)
                : 0,
              4,
            );
            item.earlyAvgRoomArea = Math.abs(item.earlyAvgRoomArea);
          }
          item.earlySumPrice = _.round(
            preItem
              ? _.toNumber(preItem.statisticsSumPrice) - _.toNumber(preItem.statisticsSignSumPrice)
              : _.toNumber(item.earlySumPrice),
            4,
          );
          // 本月可售均价
          if (isParking * 1 === 1) {
            item.earlyAvgPrice = _.round(
              item.earlyRoomCount
                ? _.toNumber(item.earlySumPrice) / _.toNumber(item.earlyRoomCount)
                : 0,
              4,
            );
            item.earlyAvgPrice = Math.abs(item.earlyAvgPrice);
          } else {
            item.earlyAvgPrice = _.round(
              item.earlyRoomArea
                ? _.toNumber(item.earlySumPrice) / _.toNumber(item.earlyRoomArea)
                : 0,
              4,
            );
            item.earlyAvgPrice = Math.abs(item.earlyAvgPrice);
          }

          // 本月签约 均价 = 本月可售 均价
          item.earlySignAvgPrice = _.toNumber(
            _.toNumber(item.earlySignSumPrice) === 0 ? 0 : _.round(item.earlyAvgPrice, 4),
          );
          item.earlySignAvgPrice = Math.abs(item.earlySignAvgPrice);
          // 如果本月可售金额 - 本月签约金额 > 0 | 本月签约套数面积 = 本月可售套数面积 --- Begin
          if (item.earlySumPrice - item.earlySignSumPrice !== 0) {
            // 车位数 = 金额 / 均价
            // 套数 = 面积 / 套均面积(本月可售)
            if (isParking * 1 === 1) {
              item.earlySignRoomCount = _.round(
                item.earlySignAvgPrice
                  ? _.toNumber(item.earlySignSumPrice) / _.toNumber(item.earlySignAvgPrice)
                  : 0,
                5,
              );
            } else {
              // 金额(万元) / 均价 = 面积
              item.earlySignRoomArea = _.round(
                item.earlySignAvgPrice
                  ? _.toNumber(item.earlySignSumPrice) / _.toNumber(item.earlySignAvgPrice)
                  : 0,
                4,
              );
              // 套数 = 面积 / 套均面积(本月可售)
              item.earlySignRoomCount = _.round(
                item.earlyAvgRoomArea
                  ? _.toNumber(item.earlySignRoomArea) / _.toNumber(item.earlyAvgRoomArea)
                  : 0,
                5,
              );
            }
            item.earlyCanSignRoomCount = _.round(
              _.toNumber(item.earlyRoomCount) - _.toNumber(item.earlySignRoomCount),
              5,
            );
          }
          if (item.earlySumPrice - item.earlySignSumPrice === 0) {
            if (isParking * 1 === 1) {
              item.earlySignRoomCount = _.round(item.earlyRoomCount, 5);
            } else {
              // 金额(万元) / 均价 = 面积
              item.earlySignRoomArea = _.round(item.earlyRoomArea, 4);
              // 套数 = 面积 / 套均面积(本月可售)
              item.earlySignRoomCount = _.round(item.earlyRoomCount, 5);
            }
            item.earlyCanSignRoomCount = _.round(0, 5);
          }
          // 如果本月可售金额 - 本月签约金额 = 0 | 本月签约套数面积 = 本月可售套数面积 --- End

          // (月初存货剩余可签) = 本月可售套数 - 本月签约套数
          // console.log(item.earlySignRoomCount, item.earlyRoomCount, item.earlySignRoomCount)

          // 新供
          // 本月签约 均价 = 本月可售 均价
          item.supplySignAvgPrice = _.toNumber(
            _.toNumber(item.supplySignSumPrice) === 0 ? 0 : _.round(item.supplyAvgPrice, 4),
          );
          item.supplySignAvgPrice = Math.abs(item.supplySignAvgPrice);
          // 如果本月可售金额 - 本月新供金额 = 0 | 本月新供套数面积 = 本月可售套数面积 --- Begin
          if (item.supplySumPrice - item.supplySignSumPrice !== 0) {
            if (isParking * 1 === 1) {
              item.supplySignRoomCount = _.round(
                item.supplySignAvgPrice
                  ? _.toNumber(item.supplySignSumPrice) / _.toNumber(item.supplySignAvgPrice)
                  : 0,
                5,
              );
            } else {
              // 金额(万元) / 均价 = 面积
              item.supplySignRoomArea = _.round(
                item.supplySignAvgPrice
                  ? _.toNumber(item.supplySignSumPrice) / _.toNumber(item.supplySignAvgPrice)
                  : 0,
                4,
              );
              // 面积 / 套均面积(本月可售) = 套数
              item.supplySignRoomCount = _.round(
                item.supplyAvgRoomArea
                  ? _.toNumber(item.supplySignRoomArea) / _.toNumber(item.supplyAvgRoomArea)
                  : 0,
                5,
              );
            }
            item.supplyCanSignRoomCount = _.round(
              _.toNumber(item.supplyRoomCount) - _.toNumber(item.supplySignRoomCount),
              5,
            );
          }
          if (item.supplySumPrice - item.supplySignSumPrice === 0) {
            if (isParking * 1 === 1) {
              item.supplySignRoomCount = _.round(item.supplyRoomCount, 5);
            } else {
              // 金额(万元) / 均价 = 面积
              item.supplySignRoomArea = _.round(item.supplyRoomArea, 4);
              // 面积 / 套均面积(本月可售) = 套数
              item.supplySignRoomCount = _.round(item.supplyRoomCount, 5);
            }
            item.supplyCanSignRoomCount = _.round(0, 5);
          }
          // 如果本月可售金额 - 本月新供金额 = 0 | 本月新供套数面积 = 本月可售套数面积 --- End
          // 本月新供 - 剩余可签
        }
        // 编辑错误提示逻辑 --- Begin
        // 月初新供 - 本月签约金额 > 本月可售金额 或本月签约金额为负数
        // 日期小于当前月不标红
        if (
          _.toNumber(item.earlySumPrice) - _.toNumber(item.earlySignSumPrice) < -1 ||
          _.toNumber(item.earlySignSumPrice) < 0
        ) {
          if (dayjs(new Date(item.year, item.month, 1)) >= dayjs()) {
            item.errorEarlySignSumPrice = true;
          }
        } else {
          item.errorEarlySignSumPrice = false;
        }
        // // 本月新供 - 本月签约金额 > 本月可售金额 或本月签约金额为负数
        if (
          _.toNumber(item.supplySumPrice) - _.toNumber(item.supplySignSumPrice) < -1 ||
          _.toNumber(item.supplySignSumPrice) < 0
        ) {
          if (dayjs(new Date(item.year, item.month, 1)) >= dayjs()) {
            item.errorSupplySignSumPrice = true;
          }
        } else {
          item.errorSupplySignSumPrice = false;
        }
        // 编辑错误提示逻辑 --- End

        item.statisticsRoomCount = _.round(
          _.toNumber(item.earlyRoomCount) + _.toNumber(item.supplyRoomCount),
          5,
        );
        item.statisticsCanSignRoomCount = _.round(
          _.toNumber(item.earlyCanSignRoomCount) + _.toNumber(item.supplyCanSignRoomCount),
          5,
        );
        if (isParking * 1 === 1) {
          item.statisticsRoomArea = null;
          item.statisticsAvgRoomArea = null;
        } else {
          item.statisticsRoomArea = _.round(
            _.toNumber(item.earlyRoomArea) + _.toNumber(item.supplyRoomArea),
            4,
          );
          item.statisticsAvgRoomArea = _.round(
            item.statisticsRoomCount
              ? _.toNumber(item.statisticsRoomArea) / _.toNumber(item.statisticsRoomCount)
              : 0,
            4,
          );
          item.statisticsAvgRoomArea = Math.abs(item.statisticsAvgRoomArea);
        }
        item.statisticsSumPrice = _.round(
          _.toNumber(item.earlySumPrice) + _.toNumber(item.supplySumPrice),
          4,
        );
        if (isParking * 1 === 1) {
          item.statisticsAvgPrice = _.round(
            item.statisticsRoomCount
              ? _.toNumber(item.statisticsSumPrice) / _.toNumber(item.statisticsRoomCount)
              : 0,
            4,
          );
          item.statisticsAvgPrice = Math.abs(item.statisticsAvgPrice);
        } else {
          item.statisticsAvgPrice = _.round(
            item.statisticsRoomArea
              ? _.toNumber(item.statisticsSumPrice) / _.toNumber(item.statisticsRoomArea)
              : 0,
            4,
          );
          item.statisticsAvgPrice = Math.abs(item.statisticsAvgPrice);
        }
        item.statisticsSignRoomCount = _.round(
          _.toNumber(item.earlySignRoomCount) + _.toNumber(item.supplySignRoomCount),
          5,
        );
        if (isParking * 1 === 1) {
          item.statisticsSignRoomArea = null;
        } else {
          item.statisticsSignRoomArea = _.round(
            _.toNumber(item.earlySignRoomArea) + _.toNumber(item.supplySignRoomArea),
            4,
          );
        }
        item.statisticsSignSumPrice = _.round(
          _.toNumber(item.earlySignSumPrice) + _.toNumber(item.supplySignSumPrice),
          4,
        );
        if (isParking * 1 === 1) {
          item.statisticsSignAvgPrice = _.round(
            item.statisticsSignRoomCount
              ? _.toNumber(item.statisticsSignSumPrice) / _.toNumber(item.statisticsSignRoomCount)
              : 0,
            4,
          );
          item.statisticsSignAvgPrice = Math.abs(item.statisticsSignAvgPrice);
        } else {
          item.statisticsSignAvgPrice = _.round(
            item.statisticsSignRoomArea
              ? _.toNumber(item.statisticsSignSumPrice) / _.toNumber(item.statisticsSignRoomArea)
              : 0,
            4,
          );
          item.statisticsSignAvgPrice = Math.abs(item.statisticsSignAvgPrice);
        }
        item.isParking = isParking;
        plans.push(item);
      });
    }
  });
  return plans;
};

// 删除归属月份之后的数据
const removeLastInvalidPlans = (plansx, affiliationMonth) => {
  const plans = _.cloneDeep(plansx);
  // 签约时间大于归属月份时间
  const isAffiliationMonthAfter =
    dayjs(_.last(plans).signPlanTime).format('YYYY-MM') > dayjs(affiliationMonth).format('YYYY-MM');
  // 数据里的值是否为空
  const isStatisticsCanSignRoomCount = _.last(plans).statisticsCanSignRoomCount === 0;
  const isStatisticsSignRoomCount = _.last(plans).statisticsSignRoomCount === 0;
  const isStatisticsSignRoomArea =
    _.last(plans).statisticsSignRoomArea === 0 || _.last(plans).statisticsSignRoomArea === null;
  const isSupplySignRoomArea =
    _.last(plans).supplySignRoomArea === 0 || _.last(plans).supplySignRoomArea === null;
  const isEarlySignRoomArea =
    _.last(plans).earlySignRoomArea === 0 || _.last(plans).earlySignRoomArea === null;
  const isEarlySumPrice = _.last(plans).earlySumPrice === 0 || _.last(plans).earlySumPrice === null;
  const isEarlySignSumPrice =
    _.last(plans).earlySignSumPrice === 0 || _.last(plans).earlySignSumPrice === null;
  const isSupplySumPrice =
    _.last(plans).supplySumPrice === 0 || _.last(plans).supplySumPrice === null;
  const isSupplySignSumPrice =
    _.last(plans).supplySignSumPrice === 0 || _.last(plans).supplySignSumPrice === null;
  const isValue =
    isStatisticsCanSignRoomCount &&
    isStatisticsSignRoomCount &&
    isStatisticsSignRoomArea &&
    isSupplySignRoomArea &&
    isEarlySignRoomArea &&
    isEarlySumPrice &&
    isEarlySignSumPrice &&
    isSupplySumPrice &&
    isSupplySignSumPrice;
  // 删除归属月份之后为空的数据
  if (!_.isEmpty(plans) && isValue && isAffiliationMonthAfter) {
    return removeLastInvalidPlans(_.slice(plans, 0, plans.length - 1), affiliationMonth);
  }
  return plans;
};

// 删除供货计划之前的数据
const removeFirstInvalidPlans = plansx => {
  const plans = _.cloneDeep(plansx);
  // 数据里的值是否为空
  const isStatisticsCanSignRoomCount = _.first(plans).statisticsCanSignRoomCount === 0;
  const isStatisticsSignRoomCount = _.first(plans).statisticsSignRoomCount === 0;
  const isStatisticsSignRoomArea =
    _.first(plans).statisticsSignRoomArea === 0 || _.first(plans).statisticsSignRoomArea === null;
  const isSupplySignRoomArea =
    _.first(plans).supplySignRoomArea === 0 || _.first(plans).supplySignRoomArea === null;
  const isEarlySignRoomArea =
    _.first(plans).earlySignRoomArea === 0 || _.first(plans).earlySignRoomArea === null;
  const isEarlySumPrice =
    _.first(plans).earlySumPrice === 0 || _.first(plans).earlySumPrice === null;
  const isEarlySignSumPrice =
    _.first(plans).earlySignSumPrice === 0 || _.first(plans).earlySignSumPrice === null;
  const isSupplySumPrice =
    _.first(plans).supplySumPrice === 0 || _.first(plans).supplySumPrice === null;
  const isSupplySignSumPrice =
    _.first(plans).supplySignSumPrice === 0 || _.first(plans).supplySignSumPrice === null;
  const isValue =
    isStatisticsCanSignRoomCount &&
    isStatisticsSignRoomCount &&
    isStatisticsSignRoomArea &&
    isSupplySignRoomArea &&
    isEarlySignRoomArea &&
    isEarlySumPrice &&
    isEarlySignSumPrice &&
    isSupplySumPrice &&
    isSupplySignSumPrice;
  // 删除供货计划之前的kong数据
  if (!_.isEmpty(plans) && isValue) {
    return removeFirstInvalidPlans(_.slice(plans, 1, plans.length));
  }
  return plans;
};

const getPlans4Save = (plansx, affiliationMonth) => {
  const plans = _.cloneDeep(plansx);
  const afterDeletionItem = removeLastInvalidPlans(plans, affiliationMonth);
  // const beforeDeletionItem = removeFirstInvalidPlans(afterDeletionItem);
  // 删除归属月份之后的数据 剩下的数据转换时间格式
  const list = afterDeletionItem.map(item => {
    const x = item;
    x.signPlanTime = dayjs(item.signPlanTime).format('YYYY-MM-DDTHH:mm:ss');
    return x;
  });
  return list;
};

const recalculateSignDatesErrors = (signDatesx, contractPlanItems) => {
  console.log(contractPlanItems, 'contractPlanItems');
  const signDates = _.cloneDeep(signDatesx);
  signDates.forEach(elementYear => {
    const y = elementYear;
    y.error = false;
    if (elementYear.months && elementYear.months.length > -1) {
      elementYear.months.forEach(elementMonth => {
        const m = elementMonth;
        m.error = false;
        const foundItems = _.filter(
          contractPlanItems,
          item => elementYear.key === item.year && elementMonth.key === item.month,
        );
        if (
          foundItems &&
          foundItems.length > 0 &&
          (foundItems[0].errorEarlySignSumPrice || foundItems[0].errorSupplySignSumPrice)
        ) {
          m.error = true;
          y.error = true;
        }
      });
    }
  });
  return signDates;
};

// 取实际值 --- Begin
const precalculatePlans = (affiliationMonth, versionType, plansx) => {
  const plans = plansx;
  plans.forEach(element => {
    const plan = element;
    // && versionType !== 'investment'
    if (dayjs(plan.signPlanTime) < dayjs(affiliationMonth)) {
      plan.earlySignRoomCount = plan.earlySignRoomCountActual;
      plan.earlySignRoomArea = plan.earlySignRoomAreaActual;
      plan.earlySignAvgPrice = plan.earlySignAvgPriceActual;
      plan.earlySignSumPrice = plan.earlySignSumPriceActual;
      plan.supplySignRoomCount = plan.supplySignRoomCountActual;
      plan.supplySignRoomArea = plan.supplySignRoomAreaActual;
      plan.supplySignAvgPrice = plan.supplySignAvgPriceActual;
      plan.supplySignSumPrice = plan.supplySignSumPriceActual;
    }
  });
  return plans;
};
// 取实际值 --- End

const Model = {
  namespace: 'ContractPlanProductTypeDetail',
  state: initData,
  effects: {
    /* 点击保存 */
    *savePlans({ payload }, { call, select }) {
      /* 取归属年月 */
      const affiliationMonth = yield select(
        state => state.ContractPlanProductTypeDetail.affiliationMonth,
      );
      /* 取版本ID */
      const versionId = yield select(state => state.ContractPlanProductTypeDetail.versionId);
      /* 取版本详情ID */
      const signPlanVersionId = yield select(
        state => state.ContractPlanProductTypeDetail.signPlanVersionId,
      );
      /* 取编制完的签约计划数据 */
      const editOkItem = yield select(
        state => state.ContractPlanProductTypeDetail.contractPlanItems,
      );
      const signPlanDetailList = getPlans4Save(editOkItem, affiliationMonth);
      const response = yield call(api.saveProductSignPlanUsingPUT, {
        data: {
          signPlanDetailList,
          versionId, // 版本id
          signPlanVersionId, // 第一条数据的id
        },
      });
      if (payload.callback) payload.callback(response);
    },
    /* 查询产品构成列表##########产品构成下拉框初始数据################ */
    *getProducts({ payload }, { call, put }) {
      const response = yield call(api.getProductListUsingGET, payload);
      const products = response && response.data ? response.data : [];
      yield put({
        type: 'save',
        payload: {
          products,
        },
      });
    },
    /* 全盘签约概览 */
    *getProjectProducts({ payload }, { call, put, select }) {
      // get 当前年月
      let year = yield select(state => state.ContractPlanProductTypeDetail.year);
      const initYear = yield select(state => state.ContractPlanProductTypeDetail.initYear);
      const month = yield select(state => state.ContractPlanProductTypeDetail.month);
      if (!year) {
        year = initYear;
      }

      // request 全盘签约概览接口
      const response = yield call(api.getProjectProductListUsingGET, {
        params: { ...payload.params, year, month },
      });

      const projectProducts = response && response.data ? response.data : [];
      yield put({
        type: 'save',
        payload: {
          projectProducts,
        },
      });
      if (payload.callback) {
        payload.callback(projectProducts, year);
      }
    },
    /* 查询产品构成的签约计划 */
    *init({ payload, callback }, { call, put }) {
      const response = yield call(api.getProductSignPlanUsingPOST, payload);
      if (
        response &&
        response.data &&
        response.data.signPlanDetailDtoList &&
        response.data.signPlanDetailDtoList.length > 0
      ) {
        const result = response.data;
        const {
          versionId /* 签约版本ID */,
          versionType /* 版本类型 */,
          signDetailProductDto /* 当前产品构成信息 */,
          supplySize /* 总供货批次 */,
          supplyPlanSize /* 未供货批次 */,
          supplyActualSize /* 已供货批次 */,
          affiliationMonth /* 版本归属年月 */,
          signPlanDetailDtoList /* 签约计划数据 */,
        } = result;
        /* 是否车位楼栋 */
        const { isParking } = _.last(signPlanDetailDtoList);
        /* 根据签约计划生成年月 */
        let signDates = recalculateSignDates(signPlanDetailDtoList);
        /* 签约详情id 后端用的 */
        const signPlanVersionId = signPlanDetailDtoList[0].id;

        // 预处理  给过来套数两个字段 汇总到一个字段内
        let contractPlanItems = precalculatePlans(
          affiliationMonth,
          versionType,
          signPlanDetailDtoList,
        );
        contractPlanItems = recalculatePlans(signDates, signPlanDetailDtoList, affiliationMonth);
        // 重新计算 给signDates加上错误提示
        signDates = recalculateSignDatesErrors(signDates, contractPlanItems);

        let canSignRoomCount = 0;
        if (contractPlanItems && contractPlanItems.length > 0) {
          canSignRoomCount = _.last(contractPlanItems).statisticsCanSignRoomCount;
        }

        // 默认显示的年月 Begin
        let initYear = 0;
        let initMonth = null;
        const isThatYear = _.filter(
          signDates,
          elementYear => elementYear.key * 1 === new Date().getUTCFullYear(),
        );
        if (isThatYear.length > 0) {
          const isMonthClick = _.filter(
            isThatYear[0].months,
            elementMonth => elementMonth.editable && elementMonth.clickable,
          );
          initYear = isThatYear[0].key * 1;
          initMonth =
            _.filter(
              isMonthClick,
              elementMonth => elementMonth.key === new Date().getUTCMonth() + 1,
            ).length > 0
              ? new Date().getUTCMonth() + 1
              : isMonthClick[0].key;
        }
        if (isThatYear.length <= 0) {
          signDates.forEach(elementYear => {
            elementYear.months.forEach(elementMonth => {
              if (elementMonth.editable && elementMonth.clickable && initYear === 0) {
                initYear = elementYear.key * 1;
                initMonth = elementMonth.key * 1;
              }
            });
          });
        }
        // 默认显示的年月 End
        yield put({
          type: 'save',
          payload: {
            initYear,
            year: null,
            month: initMonth,
            affiliationMonth,
            signDetailProductDto,
            versionId,
            signDates,
            isParking,
            supplySize,
            supplyPlanSize,
            supplyActualSize,
            canSignRoomCount,
            supplyPlanItems: result.productSupplyDetailList,
            contractPlanItems,
            signPlanVersionId,
            versionDetails: {
              //  版本状态
              versionState: result.versionState,
              //  签约计划版本全路径名称
              signFullName: result.signFullName,
              //  供货计划版本全路径名称
              supplyFullName: result.supplyFullName,
            },
          },
        });
      } else {
        yield put({
          type: 'save',
          payload: initData,
        });
      }

      if (callback && typeof callback === 'function') {
        callback(response.data);
      }
    },
    *changeYearMonth({ payload, callback }, { call, put }) {
      console.log(payload, 'payload');
      yield put({
        type: 'save',
        payload,
      });
    },
    *canSignPrice({ payload, callback }, { call, put }) {
      const { canSignPrice } = payload;
      yield put({
        type: 'save',
        payload: {
          canSignPrice,
        },
      });
    },
  },
  reducers: {
    clear() {
      return {
        ...initData,
      };
    },
    changeSignRoomCount(state, action) {
      let { signDates } = state;
      let contractPlanItems = _.cloneDeep(state.contractPlanItems);
      contractPlanItems.forEach(element => {
        const item = element;
        if (
          item.year * 1 === action.payload.year * 1 &&
          element.month * 1 === action.payload.month * 1
        ) {
          if (action.payload.key === 'early') {
            item.earlySignRoomCount = action.payload.value;
          }
          if (action.payload.key === 'supply') {
            item.supplySignRoomCount = action.payload.value;
          }
        }
      });
      // 重新计算全部签约计划
      contractPlanItems = recalculatePlans(signDates, contractPlanItems, state.affiliationMonth);
      // 重新计算 给signDates加上错误提示
      signDates = recalculateSignDatesErrors(signDates, contractPlanItems);
      let canSignRoomCount = 0;
      if (contractPlanItems && contractPlanItems.length > 0) {
        canSignRoomCount = _.last(contractPlanItems).statisticsCanSignRoomCount;
      }
      return {
        ...state,
        signDates,
        canSignRoomCount,
        contractPlanItems,
      };
    },
    changeSignMoney(state, action) {
      let { signDates } = state;
      let contractPlanItems = _.cloneDeep(state.contractPlanItems);
      contractPlanItems.forEach(element => {
        const item = element;
        if (
          item.year * 1 === action.payload.year * 1 &&
          element.month * 1 === action.payload.month * 1
        ) {
          if (action.payload.key === 'early') {
            item.earlySignSumPrice = action.payload.value * 10000;
          }
          if (action.payload.key === 'supply') {
            item.supplySignSumPrice = action.payload.value * 10000;
          }
        }
      });
      // 重新计算全部签约计划
      contractPlanItems = recalculatePlans(signDates, contractPlanItems, state.affiliationMonth);
      // 重新计算 给signDates加上错误提示
      signDates = recalculateSignDatesErrors(signDates, contractPlanItems);
      let canSignRoomCount = 0;
      if (contractPlanItems && contractPlanItems.length > 0) {
        canSignRoomCount = _.last(contractPlanItems).statisticsCanSignRoomCount;
      }
      return {
        ...state,
        signDates,
        canSignRoomCount,
        contractPlanItems,
      };
    },
    addYear(state, action) {
      let signDates = addSignDate(state.signDates);
      // 重新计算全部签约计划
      const contractPlanItems = recalculatePlans(
        signDates,
        state.contractPlanItems,
        state.affiliationMonth,
      );
      // 重新计算 给signDates加上错误提示
      signDates = recalculateSignDatesErrors(signDates, contractPlanItems);
      let canSignRoomCount = 0;
      if (contractPlanItems && contractPlanItems.length > 0) {
        canSignRoomCount = _.last(contractPlanItems).statisticsCanSignRoomCount;
      }
      return {
        ...state,
        canSignRoomCount,
        signDates,
        contractPlanItems,
      };
    },
    removeYear(state, action) {
      let signDates = _.filter(
        state.signDates,
        item => item.key !== _.toNumber(action.payload.year),
      );
      const contractPlanItems = recalculatePlans(
        signDates,
        state.contractPlanItems,
        state.affiliationMonth,
      );
      // 重新计算 给signDates加上错误提示
      signDates = recalculateSignDatesErrors(signDates, contractPlanItems);
      let canSignRoomCount = 0;
      if (contractPlanItems && contractPlanItems.length > 0) {
        canSignRoomCount = _.last(contractPlanItems).statisticsCanSignRoomCount;
      }
      return {
        ...state,
        signDates,
        canSignRoomCount,
        contractPlanItems,
      };
    },
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
